package com.cs.netty.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.nio.charset.Charset;

/**
 * @ClassName: NettyByteBuf02
 * @Description: TODO
 * @Author: kevin
 * @Date: 2020/8/12 15:52
 * @Version: 1.0
 */
public class NettyByteBuf02 {
    public static void main(String[] args) {
        // 创建ByteBuf
        ByteBuf byteBuf = Unpooled.copiedBuffer("hello,广州", Charset.forName("utf-8"));

        // 使用相关的方法
        if (byteBuf.hasArray()) {
            byte[] content = byteBuf.array();

            // 将 content 转为字符串
            System.out.println(new String(content, Charset.forName("utf-8")));

            System.out.println("byteBuf=" + byteBuf);

            System.out.println(byteBuf.arrayOffset()); // 0
            System.out.println(byteBuf.readerIndex()); // 0
            System.out.println(byteBuf.writerIndex()); // 12
            System.out.println(byteBuf.capacity()); // 24

//            System.out.println(byteBuf.readByte());
            System.out.println(byteBuf.getByte(0)); // 不会影响readByte

            int len = byteBuf.readableBytes(); // 可读取的字节数 12
            System.out.println("len=" + len);

            // 使用 for 取出各个字节
//            for (int i = 0; i < len; i++) {
//                System.out.println((char) byteBuf.getByte(i));
//            }

            // 按照某个范围读取
            System.out.println(byteBuf.getCharSequence(0, 6, Charset.forName("utf-8")));
            System.out.println(byteBuf.getCharSequence(6, 6, Charset.forName("utf-8")));
        }
    }
}
